const API = require('../../utils/api')
const pathUrl = require('../../utils/common.js')
Page({
  data: {
    videos: [],
    searchKey: '',
    currentLevel: '全部',
    currentCategory: '全部',
    levels: [
      { id: '全部', name: '全部' },
      { id: '初级', name: '初级' },
      { id: '中级', name: '中级' },
      { id: '高级', name: '高级' },
      { id: '专业', name: '专业' }
    ],
    categories: [
      { id: '全部', name: '全部' },
      { id: '基础教学', name: '基础教学' },
      { id: '进阶技巧', name: '进阶技巧' },
      { id: '战术指导', name: '战术指导' },
      { id: '体能训练', name: '体能训练' }
    ],
    page: 1,
    hasMore: true,
    loading: false
  },
  onLoad() {
    this.loadVideos()
  },
  onShow() {
  },
  async loadVideos(reset = true) {
    // 如果当前正在加载中，避免重复加载
    if (this.data.loading) return
    
    if (reset) {
      this.setData({ page: 1, hasMore: true })
    }
    if (!this.data.hasMore && !reset) return
    
    this.setData({ loading: true })
    
    try {
      const res = await API.teachingVideoList({
        title: this.data.searchKey,
        level: this.data.currentLevel === '全部' ? '' : this.data.currentLevel,
        category: this.data.currentCategory === '全部' ? '' : this.data.currentCategory,
        pageNum: this.data.page,
        pageSize: 10
      })
      
      const newVideos = res.records || [];
      
      // 处理视频URL和封面图路径
      for(let i=0; i<newVideos.length; i++){
        newVideos[i].videoUrl = pathUrl + newVideos[i].videoUrl;
        if(newVideos[i].cover) {
          newVideos[i].cover = pathUrl + newVideos[i].cover;
        }
      }
      
      // 根据返回的数据量判断是否还有更多数据
      const hasMoreData = newVideos.length === 10
      
      this.setData({
        videos: reset ? newVideos : [...this.data.videos, ...newVideos],
        page: this.data.page + 1,
        hasMore: hasMoreData,
        loading: false
      })
    } catch (err) {
      console.error('加载教学视频失败:', err)
      wx.showToast({
        title: '加载失败，请重试',
        icon: 'none'
      })
      this.setData({ loading: false })
    }
  },

  onSearch(e) {
    this.setData({ searchKey: e.detail.value })
    this.loadVideos()
  },

  switchLevel(e) {
    const level = e.currentTarget.dataset.id
    this.setData({ currentLevel: level })
    this.loadVideos()
  },

  switchCategory(e) {
    const category = e.currentTarget.dataset.category
    this.setData({ currentCategory: category })
    this.loadVideos()
  },

  goToVideoDetail(e) {
    const item = e.currentTarget.dataset.item
    wx.navigateTo({
      url: '/pages/teaching-detail/teaching-detail?item='+JSON.stringify(item)
    })
  },

  loadMore() {
    this.loadVideos(false)
  },

  onShareAppMessage() {
    return {
      title: '网球教学视频大全',
      path: '/pages/teaching/teaching',
      imageUrl: '/images/share-video.jpg'
    }
  },
  
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    // 当页面滚动到底部时，加载更多数据
    this.loadMore()
  }
})